package com.hourses.service.impl;

import com.alibaba.fastjson2.JSON;
import com.hourses.mapper.BrandMapper;
import com.hourses.pojo.Brand;
import com.hourses.pojo.Result;
import com.hourses.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Description:
 * @Author:LiTao
 * @Date:2025/5/1 18:27
 */
@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    //查询品牌列表
    @Autowired
    private BrandMapper brandMapper;
    @Override
    public Result selectBrandList() {
        //先看看缓存里面有没有
        String redisBrands = redisTemplate.opsForValue().get("brands");
        if (StringUtils.hasText(redisBrands)){
            //如果缓存中有
            return Result.ok(JSON.parseArray(redisTemplate.opsForValue().get("brands")));
        }
        //如果缓存中没有
        //先从数据库中查
        List<Brand> brands = brandMapper.selectBrandList();
        //查到以后存入缓存中去
        redisTemplate.opsForValue().set("brands",JSON.toJSONString(brands));
        return Result.ok(brands);
    }
}
